package File;

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

//本类用与练习文件复制综合案例
public class TestCopyFile {

    public static void main(String[] args) throws Exception {
        //1.提示并接受用户输入的源文件路径和目标位置
        System.out.println("请您输入源文件路径：");
        String f = new Scanner(System.in).nextLine();
        System.out.println("请您输入目标位置：");
        String t = new Scanner(System.in).nextLine();

        ZFCopy(f,t);//用字符流完成复制案例
        ZjCopy(f,t);//用字节流完成复制案例
        
    }

    private static void ZjCopy(String f,String t) throws FileNotFoundException {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        try{
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(new FileOutputStream(t));
            int b;
            while ((b=in.read())!=-1){
                out.write(b);
            }
            System.out.println("文件复制成功");

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void ZFCopy(String f,String t) {
        //1.定义在整个方法中都生效的局部变量，手动初始化值为null
        Reader in = null;
        Writer out = null;
        //2.由于代码可能会发生异常，所以需要try-catch-finally结构
        try{
            //3.创建高效/缓冲字符输入流与输出流对象
            in = new BufferedReader(new FileReader(new File(f)));
            out = new BufferedWriter(new FileWriter(new File(t)));
            int a ;

            while ((a= in.read())!=-1){
                out.write(a);//将本次循环草你个源文件读到的内容写出到目标文件中
            }
            System.out.println("文件复制成功");


        }catch(Exception e){
            e.printStackTrace();

        }finally {
            //关流是有顺序的：如果有多个流，最后创建的流最先关闭
            //多条关流语句需要各自try--catch
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
